package com.itheima;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class FilterAll implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("text/html;charset=UTF-8");
        Object username = request.getSession().getAttribute("username");
        String uri = request.getRequestURI();
        //可直接放行的资源
        if (uri.endsWith("ServletLogin")||uri.endsWith("login.jsp")){
            filterChain.doFilter(request,response);
            return;
        }
        //放行其他资源需要判断是否登陆
        if (username!=null){
            filterChain.doFilter(request,response);
            return;
        }else{
            response.getWriter().write("请先登陆");
            response.setHeader("Refresh","1;URL=login.jsp");
        }
    }
}
